﻿using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using MiniJson;
using PandoraEditor;
using UnityEngine;
using UnityEngine.Networking;
using JsonUtility = MiniJson.JsonUtility;

namespace NeatlyEditor
{
    public static class DingDingHelper
    {
        public static async Task PostCards(string title, Dictionary<string, string> urls)
        {
            JsonValue data = new JsonValue();
            data.Add("msgtype", "actionCard");
            JsonValue actionCard = new JsonValue();
            actionCard.Add("title", "package");
            actionCard.Add("text", title);
            JsonValue btns = new JsonValue(new List<JsonValue>());
            foreach (var info in urls)
            {
                var item = new JsonValue();
                item.Add("title", info.Key);
                item.Add("actionURL", info.Value);
                btns.Add(item);
            }

            actionCard.Add("btns", btns);
            data.Add("actionCard", actionCard);
            Debug.Log(JsonUtility.ToString(data));
            using (UnityWebRequest request = new UnityWebRequest(BuildSetting.LocalServerSetting.url_dingding, "POST"))
            {
                byte[] bodyRaw = Encoding.UTF8.GetBytes(JsonUtility.ToString(data));
                request.uploadHandler = new UploadHandlerRaw(bodyRaw);
                request.downloadHandler = new DownloadHandlerBuffer();
                request.SetRequestHeader("Content-Type", "application/json");
                var operation = request.SendWebRequest();

                while (!operation.isDone)
                {
                    await Task.Yield();
                }

                if (request.result == UnityWebRequest.Result.Success)
                {
                    Debug.Log(request.downloadHandler.text);
                    return;
                }

                Debug.LogError($"Request failed: {request.error}");
            }
        }
    }
}